package com.huaxin.hxcloud.find;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.HxCommentStateBean;
import com.huaxin.common.Global;
import com.huaxin.common.media.view.PhotoAddView;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.picture.GridImageAdapter;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.view.RefreshDataEvent;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 发送评论界面
 * Created by hebing on 2017/4/17.
 */

public class ReportSayActivity extends BaseActivity {


    @BindView(R.id.see_img)
    ImageView      mSeeImg;
    @BindView(R.id.see_type_tv)
    TextView       mSeeTypeTv;
    @BindView(R.id.right_img)
    ImageView      mRightImg;
    @BindView(R.id.see_state_tv)
    TextView       mSeeStateTv;
    @BindView(R.id.permission_rv)
    RelativeLayout mPermissionRv;
    private String path;

    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.find_commit_giveup)
    TextView     giveupCommit;
    @BindView(R.id.find_commit)
    TextView     commitText;
    @BindView(R.id.find_desEdit)
    EditText     editText;
    @BindView(R.id.find_photo_add_view)
    PhotoAddView photoAddView;
    @BindView(R.id.find_commit_name)
    TextView     textName;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private List<LocalMedia> selectList  = new ArrayList<>();
    private int              mIssueRange = 4;//所有行业能见
    private GridImageAdapter mImageAdapter;
    private static final String TAG = "ReportSayActivity";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_find_report;
    }

    @Override
    public void initView() {
        super.initView();
        photoAddView.setMaxSize(9);
        EventBus.getDefault().register(this);
        loadText(textName, Global.user.getNickName());

    }

    @Override
    public void initData() {
        super.initData();

        mImageAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mImageAdapter);

    }


    @OnClick({R.id.find_commit_giveup, R.id.find_commit, R.id.permission_rv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.find_commit_giveup:
                finish();
                break;
            case R.id.find_commit:
                submitForm();
                break;
            case R.id.permission_rv: //评论状态选择
                Intent intent = new Intent(this, HxCommentStateActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    mImageAdapter.setList(selectList);
                    mImageAdapter.notifyDataSetChanged();
                    Log.d(TAG, selectList.size() + "-->" + selectList.get(0));
                    break;
            }
        }
    }


    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(ReportSayActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(9)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(false)// 是否可预览视频
                    .enablePreviewAudio(false) // 是否可播放音频
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(false)// 是否压缩
                    .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .withAspectRatio(16, 9)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .isGif(true)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(false)// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                    //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled() // 裁剪是否可旋转图片
                    //.scaleEnabled()// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };


    /**
     * @desc 提交表单
     * @author songxf
     * created at 2017/6/27 17:21
     */
    private void submitForm() {
        String editText = this.editText.getText().toString();
        if (TextUtils.isEmpty(editText) && selectList.size() == 0) {
            ToastUtil.showToast("没有内容");
            return;
        }
        List<String> imageDatas = new ArrayList<>();
        for (int i = 0; i < selectList.size(); i++) {
            String path = selectList.get(i).getPath();
            imageDatas.add(path);
        }
        final ProgressDialog dialog = DialogUtil.getWaitDialog(ReportSayActivity.this, "提交中...");
        dialog.show();
        Call<BaseDTO> call = RequestHelper.getRequestApi().commitFindSay(editText, RequestHelper.submitFileParts(imageDatas.toArray(new String[imageDatas.size()])), mIssueRange);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                dialog.dismiss();
                if (response.isSuccessful()) {
                    if (baseDTO != null && baseDTO.getMsg().equalsIgnoreCase("success")) {
                        ToastUtil.showToast(getString(R.string.submit_success));
                        //发送广播，用来更新数据
                        EventBus.getDefault().post(new RefreshDataEvent(true));
                        finish();
                    } else {
                        ToastUtil.showToast(getString(R.string.submit_faile));
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.submit_faile));
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast(getString(R.string.network_faile));
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentStateEvent(HxCommentStateEventBus message) {
        int position = message.mPosition;
        HxCommentStateBean stateBean = message.getStateBean();
        Log.d(TAG, "commentStateEvent: ---->" + stateBean.toString());
        String type = stateBean.getType();
        String typeDes = stateBean.getTypeDes();
        mIssueRange = stateBean.getIssueRange();
        mSeeTypeTv.setText(type);
        mSeeStateTv.setText(typeDes);
        mSeeImg.setBackgroundResource(R.drawable.see_03_03);
    }
}
